package com.atguigu.tingshu.album.config;


import com.atguigu.tingshu.album.mapper.AlbumInfoMapper;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RCountDownLatch;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ExecutorService;

@Component
public class BloomFilterConfig {

    @Autowired
    RedissonClient redissonClient;
    @Autowired
    ExecutorService executorService;
    @Autowired
    AlbumInfoMapper albumInfoMapper;



    @Bean
    public RBloomFilter bloomFilter() throws InterruptedException {
        //初始化布隆过滤器
        RBloomFilter<String> bloomFilter = redissonClient.getBloomFilter(RedisConstant.ALBUM_BLOOM_FILTER);
        bloomFilter.tryInit(20000000,0.03);
        //向布隆过滤器中初始化初始数据
        int pageNum=1;
        int pageSize = 1000;
        //通过总记录条数 算出多少页
        Long count = this.albumInfoMapper.selectCount(null);
        long totalPage = count/pageSize;
        totalPage = count % pageSize == 0 ? totalPage : totalPage+1;
        //
        RCountDownLatch countDownLatch = this.redissonClient.getCountDownLatch(RedisConstant.ALBUM_BF_LATCH);
        while (pageNum<totalPage){
            int finalPageNum = pageNum;
            executorService.execute(()->{
                //查询当前页的专辑数据
                Page<AlbumInfo> albumInfoPage = albumInfoMapper.selectPage(new Page<>(finalPageNum, pageSize), null);
                List<AlbumInfo> albumInfos = albumInfoPage.getRecords();
                //遍历当前页的数据放入布隆过滤器
                albumInfos.forEach(albumInfo -> {
                    bloomFilter.add(RedisConstant.ALBUM_INFO_PREFIX+albumInfo.getId());

                });
                countDownLatch.countDown();

            });
            pageNum++;
        }

        //TODO 声音数据

        //TODO 分类数据

        countDownLatch.await();

        return bloomFilter;
    }


}
